//
//  LWStatusPictureView.swift
//  Swift_Weibo_HLW
//
//  Created by huanglinwang on 16/9/25.
//  Copyright © 2016年 Linwang. All rights reserved.
//

import UIKit
import SDWebImage
//  重用标记
private let LWStatusPictureViewCellIdentifier = "LWStatusPictureViewCellIdentifier"

//  每项之间的间距
let itemMargin: CGFloat = 5
//  每项的宽度
let itemWidth = (ScreenWidth - 2 * LWHomeTabCellMargin - 2 * itemMargin) / 3


class LWStatusPictureView: UICollectionView {


    //  设置配图数据源
    var picUrls: [LWStatusPictureInfo]? {
        didSet {
            
                messageLabel.text = "\(picUrls?.count ?? 0)"
                let size = calcSize(count: picUrls?.count ?? 0)
                
                //  设置约束大小
                self.snp_updateConstraints { (make) in
                    make.size.equalTo(size)
                }
            self.reloadData()
        }

        
    }

    //  MARK: --懒加载控件
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.magenta, fontSize: 20)
        return label
    }()

    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //  创建布局对象
        let flowLayout = UICollectionViewFlowLayout()
        
        //  设置大小
//        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //  水平间距
        flowLayout.minimumInteritemSpacing = itemMargin

        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //  添加控件设置约束
    private func setupUI() {
        
        backgroundColor = RandomColor()
        
        addSubview(messageLabel)
        
        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        //  注册cell
        register(LWStatusPictureViewCell.self, forCellWithReuseIdentifier: LWStatusPictureViewCellIdentifier)
        //  设置数据源代理
        self.dataSource = self

        
    }
    
    //  根据图片张数计算配图大小
    private func calcSize(count: Int) -> CGSize {
        
        //  每项之间的间距
        let itemMargin: CGFloat = 5
        //  每项的宽度
        let itemWidth = (ScreenWidth - 2 * LWHomeTabCellMargin - 2 * itemMargin) / 3
        
        if count == 1 {
            let imageUrl = picUrls!.first!.thumbnail_pic!
            //  从缓存中去取图片
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageUrl)
            //  如果image不为nil表示找到了缓存中图片
            if image != nil {
                //  注意一个问题 , 单张图片的大小 绑定数据时候图片比设置条目的大小要大,那么就会出现警告
                
                var size = image!.size
                
                //  如果图片的宽度小于指定的大小,那么需要等比计算图片的高度
                //  图片过窄处理 -> 产品处理这个问题
                //                if size.width < 80 {
                //                    //  指定宽度
                //                    let scaleWidth: CGFloat = 80
                //                    let height = scaleWidth / size.width * size.height
                //
                //                    let scaleHeight = height > 150 ? 150: height
                //
                //
                //                    size.width = scaleWidth
                //                    size.height = scaleHeight
                //                }
                
                
                //  直接指定成特定大小
//                size = CGSize(width: itemWidth, height: itemWidth)
                size = CGSize(width: size.width, height: size.height)
                //  怎么调整条目大小
                
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                //  调整单张图片 条目的大小
                flowLayout.itemSize = size
                
                return size
                
            }
            
        }
        
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //  调整单张图片 条目的大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //  计算列数
        let cols = count > 3 ? 3 : count
        //  计算行数
        let rows = (count - 1) / 3 + 1
        //  计算当前配图宽度
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        //  计算当前配图的高度
        let currentHeight = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin
        
        return CGSize(width: currentWidth, height: currentHeight)
        
    }
}

//  MARK: --UICollectionViewDataSource
extension LWStatusPictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LWStatusPictureViewCellIdentifier, for: indexPath) as! LWStatusPictureViewCell
        cell.statusPictureInfo = picUrls![indexPath.item]
        return cell
    }
}


//  自定义配图cell
class LWStatusPictureViewCell: UICollectionViewCell {
    //  设置模型数据
    var statusPictureInfo: LWStatusPictureInfo? {
        didSet {
            if let url = statusPictureInfo?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    //  MARK: --    懒加载控件
    private lazy var imageView: UIImageView = {
        
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  等比例原样显示
        view.contentMode = .scaleAspectFill
        //  会有超出范围显示,  剪切多余部分
        view.clipsToBounds = true
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        
        contentView.addSubview(imageView)
        //  imageView的大小等于contentView
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
        
        
        
    }
    
    
    
    
}





